$(function () {
    //获取url
    var url = localStorage.getItem("ajaxUrl");
    var work_id = "";
    var machine = localStorage.getItem("heatMachine");
    var work = "";
    var controlvalue_I = 2.800; //T
    var controlvalue_J = 0.500; //T
    var pass = 1;
    var focus = true;

    $(".head .icon-lishi1").on("click", function () {
        var machine = $("section span.machine").html();
        if (machine && machine != "空") {
            localStorage.setItem("heatMachine", machine);
        }
        localStorage.setItem("produce", "heat");
        window.location.href = "produce_lishi.html";
    });

    //搜索框 获取焦点
    $("#goods_id").focus();
    $("#goods_id").blur(function () {
        if (focus) {
            $("#goods_id").focus();
        }
    });

    $("div.page").on("click", "span.personal", function() {
        localStorage.removeItem("heatMachine");
        focus = false;
        $("#goods_id").blur();
    });

    $(".panel-overlay").on("click", function () {
        focus = true;
        setTimeout(function () {
            $("#goods_id").val("").focus();
        }, 1000);
    });

    //根据 id 得到 工单信息、机台信息
    getWorkFun(machine);

    function getWorkFun(machine) {
        if (machine) {
            loading_show("获取中...");
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/heat/getHeatPlanAndMaterialByMachine',
                data: {
                    machine: machine
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    loading_hide();
                    if (res.success) {
                        showplandata(res, machine);
                    } else {
                        console.log(res);
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    loading_hide();
                    console.log(error);
                    $alert(error.responseText);
                }
            });
        } else {
            $("section span.machine").html("空");
        }
    }

    $("#goods_id").on("keydown", function (event) {
        if (event.keyCode == "13") {
            if (pass == 0) {
                return
            }
            pass = 0;
            var val = $(this).val();
            $("#goods_id").val("");
            if (!val) {
                $alert("请扫描热处理机台！");
                pass = 1;
                setTimeout(function () {
                    $("#goods_id").val("").focus();
                }, 1400);
                return;
            } else {
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    type: "post",
                    url: url + '/app/heat/getHeatPlanAndMaterialByMachine',
                    data: {
                        machine: val
                    },
                    dataType: 'json',
                    json: 'callback',
                    success: function (res) {
                        pass = 1;
                        loading_hide();
                        if (res.success) {
                            $alert(val + "扫描成功");
                            showplandata(res, val);
                        } else {
                            console.log(res);
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        pass = 1;
                        loading_hide();
                        console.log(error);
                        $alert(error.responseText);
                    }
                });
            }
        }
    });
    //展示计划 数据
    function showplandata(res, machine) {
        var data = res.result;
        work = data;
        if (res.controlvalue) {
            if (res.controlvalue["I"]) {
                controlvalue_I = res.controlvalue["I"];
            }
            if (res.controlvalue["J"]) {
                controlvalue_J = res.controlvalue["J"];
            }
        }
        //填充 当前机台与当前用料
        $("section span.machine").html(machine);
        if (data.plan && data.plan.workplanNumber) {
            work_id = data.plan._id;
            $("section span.workplanNumber").html(data.plan.workplanNumber);
            $("section span.kh").html(data.plan.customerName);
            $("section span.work_mc").html(data.plan.inventoryName);
            $("section span.work_gg").html(data.plan.inventorySpecification);
            $("section span.work_djzl").html(data.plan.singleQuantity);
            $("section span.work_bzfs").html(data.plan.packMethod || "无");
            $("section span.work_klqd").html(data.plan.tensileStrength);
            $("section span.work_sll").html(data.plan.zincLayerWeight);
            $("section span.work_ylgg").html(data.plan.inventoryMaterials[0] ? data.plan.inventoryMaterials[0].inventoryMaterialSpecification : "");
            $("section span.work_weight").html(data.plan.detail.planQuantity);
            $("section span.work_completeWeight").html(data.plan.detail.completeQuantity ? Number(parseFloat(data.plan.detail.completeQuantity).toFixed(3)) : "0");
        } else {
            $("section span.workplanNumber").html("空");
            $("section span.kh").html("空");
            $("section span.work_mc").html("空");
            $("section span.work_gg").html("空");
            $("section span.work_djzl").html("空");
            $("section span.work_bzfs").html("空");
            $("section span.work_klqd").html("空");
            $("section span.work_sll").html("空");
            $("section span.work_ylgg").html("空");
            $("section span.work_weight").html("空");
            $("section span.work_completeWeight").html("空");
        }
        if (data.material && data.material.length > 0) {
            $("section div.material span.number").html(data.material[0].batch);
            $("section div.material span.gggh").html(data.material[0].inventorySteel + " " + data.material[0].inventoryDiameter);
            $("section div.material span.lh").html(data.material[0].stove);
            $("section div.material span.column").html(data.material[0].column);
            $("section div.material span.weight").html(data.material[0].quantity);
            setAllmaterial(data.material);
            // if (Number(data.material[0].quantity) < 50) {
            //     $alert("当前原料剩余重量小于50KG了，请检查", 3000);
            // }
        } else {
            $("section div.material span.number").html("空");
            $("section div.material span.gggh").html("空");
            $("section div.material span.lh").html("空");
            $("section div.material span.column").html("空");
            $("section div.material span.weight").html("空");
            setAllmaterial([]);
        }
    }

    function setAllmaterial(material) {
        // console.log(material.length)
        var allMaterialHtml = "";
        for (var i = 1; i < material.length; i++) {
            allMaterialHtml += '  <div class="card-content-inner">' +
                '<a href="#"><span class="icon iconfont icon-tui tl pull-right"></span></a>' +
                '<p><span>编号 ：</span><span class="number">' + material[i].batch + '</span></p>' +
                '<p><span>规格钢号 ：</span><span class="gggh">' + material[i].inventorySteel + " " + material[i].inventoryDiameter + '</span></p>' +
                '<p><span>炉号 ：</span><span class="lh">' + material[i].stove + '</span>&nbsp;&nbsp;<span>卷号 ：</span><span class="column">' + material[i].column + '</span></p>' +
                '<p><span>剩余重量 ：</span><span class="quantity">' + material[i].quantity + '</span></p></div>'
        }
        $(".allMaterial").empty().html(allMaterialHtml).hide();
    }

    // 点击 下箭头
    $(".material").on("click", ".aaa", function (event) {
        var classname = $(this).attr("class");
        if (classname.indexOf("icon-xiashuangjiantou") > -1) {
            $(".allMaterial").show();
            $(this).removeClass("icon-xiashuangjiantou");
            $(this).addClass("icon-shangshuangjiantou");

        } else{
            $(".allMaterial").hide();
            $(this).removeClass("icon-shangshuangjiantou");
            $(this).addClass("icon-xiashuangjiantou");
        }
    });
    //点击 上料
    $(".bnt .shangliao").on("click", function () {
        var machine = $("section span.machine").html();
        if (!machine || machine == "空") {
            $alert("请先扫描热处理机台");
            setTimeout(function () {
                $("#goods_id").val("").focus();
            }, 1400);
        } else {
            loading_show("获取中...");
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/heat/isFeedMachine',
                dataType: 'json',
                data: {
                    id: work_id,
                    machine: $("section span.machine").html()
                },
                json: 'callback',
                cache: false,
                timeout: 60000,
                success: function (res) {
                    if (res.success) {
                        var data = res.result;
                        loading_hide();
                        // var weight = $("section .material span.weight").html();
                        // //if (weight != "空" && Number(weight) > 500) return $alert("剩余重量大于500，不可上料");
                        // localStorage.setItem("work_id", work_id);
                        // localStorage.setItem("heatMachine", machine);
                        // window.location.href = "heat_sl.html";
                        if (res.nextInventoryMaterialSpecification) {
                            //$alert("收线成功，计划已更新，请知悉");
                            var html = '<span style="color: red; font-weight: bolder">请准备更换规格: ' + res.nextInventoryMaterialSpecification + '</span>';
                            $.alert(html, function () {
                                localStorage.setItem("work_id", work_id);
                                localStorage.setItem("heatMachine", machine);
                                window.location.href = "heat_sl.html";
                            });
                        } else {
                            localStorage.setItem("work_id", work_id);
                            localStorage.setItem("heatMachine", machine);
                            window.location.href = "heat_sl.html";
                        }
                    } else {
                        console.log(res);
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    //隐藏提示符 显示
                    loading_hide();

                    if (error.status == 0) {
                        $alert("请求超时，请再试一次！");
                    } else {
                        console.log(error);
                        $alert(error.responseText);
                    }
                }
            });
        }
    });

    // 点击 清楚 原料
    $(".bnt .clear").on("click", function () {
        var machine = $("section span.machine").html();
        var workplanNumber = $("section span.workplanNumber").html();
        var quantity = $("section div.material span.weight").html();
        var number = $("section div.material span.number").html();
        if (!workplanNumber || workplanNumber == "空") {
            return $alert("请先扫描机台号");
        }
        if (!machine || machine == "空") {
            $alert("请先扫描热处理机台");
        } else {
            $.confirm("当前用料剩余" + quantity + "，确认清除吗？", function () {
                loading_show("清除中...");
                $.ajax({
                    headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                    type: "post",
                    url: url + '/app/heat/clearMachinematerial',
                    dataType: 'json',
                    data: {
                        id: work_id,
                        batch: number,
                        machine: machine
                    },
                    json: 'callback',
                    cache: false,
                    timeout: 60000,
                    success: function (res) {
                        if (res.success) {
                            var data = res.result;
                            loading_hide();
                            $alert("清除成功");
                            localStorage.setItem("heatMachine", machine);
                            setTimeout(function () {
                                window.location.href = "heatfeed.html";
                            }, 1200);
                        } else {
                            console.log(res);
                            $alert(res.message);
                        }
                    },
                    error: function (error) {
                        //隐藏提示符 显示
                        loading_hide();

                        if (error.status == 0) {
                            $alert("请求超时，请再试一次！");
                        } else {
                            console.log(error);
                            $alert(error.responseText);
                        }
                    }
                });
            })
        }
    });

    //点击 退料
    $(".content").on("click", ".tl", function () {
        var workplanNumber = $("section span.workplanNumber").html();
        if (!workplanNumber || workplanNumber == "空") {
            return $alert("请先扫描机台号");
        }
        if ($(this).parent().parent().find("span.number").html() && $(this).parent().parent().find("span.number").html() != "空") {
            focus = false;
            $(".mengceng").show();
            $("div.div_tuiliao").show();
            $("div.div_tuiliao select.selfResult").val("合格").trigger("change");
            $("div.div_tuiliao input.syzl").val($(this).parent().parent().find("span.weight").html()).focus();
            $("div.div_tuiliao input.batch").val($(this).parent().parent().find("span.number").html());
        } else {
            $alert("退料编号不正确！");
        }
    });
    //点击 退料
    /*$(".bnt .returnMaterial").click(function () {
        if ($("div.material span.number").html() && $("div.material span.number").html() != "空") {
            focus = false;
            $(".mengceng").show();
            $("div.div_tuiliao").show();
            $("div.div_tuiliao input.syzl").val("").focus();
        } else {
            $alert("请先上料！");
        }
    });*/
    //点击 退料 取消
    $("div.div_tuiliao .tl_quxiao").click(function () {
        $(".mengceng").hide();
        $("div.div_tuiliao").hide();
        $("#goods_id").focus();
        focus = true;
    });
    //点击 退料 确定
    $("div.div_tuiliao .tl_queding").click(function () {
        if ($("div.div_tuiliao input.syzl").val() <= 0) {
            $alert("剩余重量应大于零");
            $("div.div_tuiliao input.syzl").focus();
        } else {
            //调用 收线 接口
            loading_show("退料中...");
            //拉丝 收线
            $.ajax({
                headers: {authorization: "Bearer " + localStorage.getItem("jwt")},
                type: "post",
                url: url + '/app/heat/heatReturnMaterial',
                data: {
                    id: work_id,
                    batch: $("div.div_tuiliao input.batch").val(),
                    machine: $("section span.machine").html(),
                    aweight: $("div.div_tuiliao input.syzl").val(),
                    selfResult: $("div.div_tuiliao select.selfResult").val()
                },
                dataType: 'json',
                json: 'callback',
                success: function (res) {
                    if (res.success) {
                        var data = res.result;
                        console.log(data);
                        loading_hide();
                        $alert("退料成功");
                        var machine = $("section span.machine").html();
                        localStorage.setItem("heatMachine", machine);
                        setTimeout(function () {
                            window.location.href = "heatfeed.html";
                        }, 1200);
                        //打印标签
                        if (res.result) {
                            if (res.result.materialType == "原料库")  {
                                //打印盘条标签
                                cordova.plugins.print.wirerodpurchaseinorder(res.result.batch, "澳森特钢", (res.result.inventorySpecification), res.result.availableQuantity, (res.result.inventoryName), function (result) {
                                }, function error(error) {
                                });
                            } else {
                                if (res.result.alias == "wire") {
                                    takeupPrint("silkTakeup", res.result);
                                } else if (res.result.alias == "heat") {
                                    takeupPrint("heatTakeup", res.result);
                                }
                            }
                        }
                    } else {
                        console.log(res);
                        loading_hide();
                        $alert(res.message);
                    }
                },
                error: function (error) {
                    console.log(error);
                    loading_hide();
                    $alert(error.responseText);
                }
            });
        }
    });

    //点击 查看计划
    $(".bnt .lookPlan").click(function () {
        var machine = $("section span.machine").html();
        var workplanNumber = $("section span.workplanNumber").html();
        if (!workplanNumber || workplanNumber == "空") {
            return $alert("请先扫描机台号");
        }
        if (!machine || machine == "空") {
            $alert("请先扫描热处理机台");
        } else {
            localStorage.setItem("heatMachine", machine);
            localStorage.setItem("heatType", "heatfeed");
            window.location.href = "heat_ckjh.html";
        }
    });

});
